<script setup>
import { onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 直接使用 store 中的 userInfo，保持状态一致
const userInfo = computed(() => userStore.userInfo)

onMounted(() => {
  // 从 localStorage 获取用户信息并同步到 store
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userStore.setUserInfo(JSON.parse(storedUserInfo))
  }
})

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清除用户信息和 token
    userStore.logout()
    ElMessage.success('已退出登录')
    
    // 跳转到登录页
    router.push('/login')
  } catch {
    // 用户取消操作
  }
}
</script>

<template>
  <div class="home-container">
    <div class="header">
      <div class="header-left">
        <h1>健研社</h1>
      </div>
      <div class="header-right">
        <div class="user-info" v-if="userInfo">
          <span class="username">{{ userInfo.username }}</span>
          <el-button type="danger" plain @click="handleLogout">
            退出登录
          </el-button>
        </div>
      </div>
    </div>
    
    <div class="content">
      <el-card class="welcome-card">
        <template #header>
          <div class="card-header">
            <span>欢迎回来</span>
          </div>
        </template>
        <div v-if="userInfo">
          <p>您好，<strong>{{ userInfo.username }}</strong>！</p>
          <p class="welcome-text">欢迎使用健研社运动管理平台</p>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.home-container {
  min-height: 100%;
  background-color: #f5f7fa;
}

.header {
  background: white;
  padding: 0 16px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-left h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.content {
  padding: 16px;
}

.welcome-card {
  width: 100%;
}

.card-header {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.welcome-text {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}

strong {
  color: #409eff;
}

/* 移动端适配 */
:deep(.el-button) {
  padding: 8px 15px;
  font-size: 13px;
}

:deep(.el-card__header) {
  padding: 14px 16px;
}

:deep(.el-card__body) {
  padding: 16px;
}
</style>
